﻿using System;

namespace Microsoft.Popfly.GameCreator.GameEngine.Behaviors
{
    public class ReverseThenKillBehavior : IBehavior
    {
        private IReverseableMotion m_behaviorToReverse;
        private Events.EventListener m_listenerToKill;
        private bool m_firstRun;
        private BehaviorOwner m_owner;
        private Events.IEventChecker m_eventCheckerToKill;

        /// <summary>
        /// Removes both a behavior and an event checker if they are not null after it reaches distance the second time
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="behaviorToReverse"></param>
        /// <param name="listenerToKill"></param>
        /// <param name="eventCheckerToKill"></param>
        public ReverseThenKillBehavior(BehaviorOwner owner, MotionBehavior behaviorToReverse, Events.EventListener listenerToKill, Events.IEventChecker eventCheckerToKill)
        {
            m_owner = owner;
            m_behaviorToReverse = behaviorToReverse;
            m_listenerToKill = listenerToKill;
            m_eventCheckerToKill = eventCheckerToKill;
            m_firstRun = true;
        }
        #region IBehavior Members

        public void Invoke(BehaviorOwner sender, Microsoft.Popfly.GameCreator.GameEngine.Events.PGCEventArgs args)
        {
            m_behaviorToReverse.Reverse();
            if (m_firstRun)
            {
                m_firstRun = false;
            }
            else
            {
                if (m_listenerToKill != null)
                {
                    m_owner.RemoveBehavior(m_listenerToKill);
                }
                if (m_eventCheckerToKill != null)
                {
                    m_owner.RemoveBehavior(m_eventCheckerToKill);
                }
            }
        }

        #endregion
    }
}
